package models

import (
	"errors"
	"group-buy/group_buy/internal/request_models"

	"xorm.io/xorm"
)

type Order struct {
	Id            int64
	Code          string
	UserId        int64
	ProductId     int64
	Amount        float64
	CompanyAmount float64
	UserName      string
	ProductName   string
	ProductCover  string
	BusinessId    int64
	DealerId      int64
	WriteOffCount int64
	FinishCount   int64
	Status        int64
	PayOrderId    string
	OpenId        string
	InviteId      int64
	PayTime       string
}

type OrderDivision struct {
	Id          int64
	OrderId     int64
	OrderCode   string
	ProductId   int64
	ProductName string
	BusinessId  int64
	DivUserId   int64
	DivAmount   float64
	DivLsUser   string
	DivStatus   int64
	DivTime     string
	PayUser     string
	PayUserId   int64
}

type OrderDivisionDetail struct {
	OrderDivision `xorm:"extends"`
	Order         `xorm:"extends"`
	Dealer        Member   `xorm:"extends"`
	InviteUser    Member   `xorm:"extends"`
	Business      Business `xorm:"extends"`
	BusinessUser  Member   `xorm:"extends"`
}

type OrderDetail struct {
	Order        `xorm:"extends"`
	Dealer       Member   `xorm:"extends"`
	InviteUser   Member   `xorm:"extends"`
	Business     Business `xorm:"extends"`
	BusinessUser Member   `xorm:"extends"`
}

func (o *Order) GetOrderDivision(engine *xorm.Engine) ([]*request_models.DivInfo, error) {
	o.CompanyAmount = o.Amount
	divs := make([]*OrderDivision, 0)
	division := &ProductDivision{ProductId: o.ProductId}
	get, err := engine.Get(division)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取分账配置失败")
	}
	bus := &Business{Id: o.BusinessId}
	get, err = engine.Get(bus)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取商家失败")
	}
	// region 商家分账
	busUser := &Member{Id: bus.UserId}
	get, err = engine.Get(busUser)
	if err != nil {
		return nil, err
	}
	if get && division.BusinessAmount > 0 {
		divs = append(divs, &OrderDivision{
			OrderId:     o.Id,
			OrderCode:   o.Code,
			ProductId:   o.ProductId,
			ProductName: o.ProductName,
			BusinessId:  o.BusinessId,
			DivUserId:   busUser.Id,
			DivAmount:   division.BusinessAmount,
			DivLsUser:   busUser.LsUser,
			DivStatus:   1,
			PayUser:     o.UserName,
			PayUserId:   o.UserId,
		})
		o.CompanyAmount -= division.BusinessAmount
	}
	//endregion

	// region 经销商分账
	dealer := &Member{Id: bus.DealerId}
	get, err = engine.Get(dealer)
	if err != nil {
		return nil, err
	}
	if get && division.DealerAmount > 0 {
		divs = append(divs, &OrderDivision{
			OrderId:     o.Id,
			OrderCode:   o.Code,
			ProductId:   o.ProductId,
			ProductName: o.ProductName,
			BusinessId:  o.BusinessId,
			DivUserId:   dealer.Id,
			DivAmount:   division.DealerAmount,
			DivLsUser:   dealer.LsUser,
			DivStatus:   1,
			PayUser:     o.UserName,
			PayUserId:   o.UserId,
		})
		o.CompanyAmount -= division.DealerAmount
	}
	//endregion

	// region 店小二分账
	if o.InviteId > 0 {
		xiaoErUser := &Member{Id: o.InviteId}
		get, err = engine.Get(xiaoErUser)
		if err != nil {
			return nil, err
		}
		if get {
			bsm := &BusinessMember{MemberId: xiaoErUser.Id, BusinessId: o.BusinessId}
			get, err = engine.Get(bsm)
			if err != nil {
				return nil, err
			}
			amount := division.InviteAmount
			if get {
				if bsm.IsIndependence != 1 {
					// region 店小二上级分账
					if bsm.InviteId > 0 {
						xiaoErPar := &Member{Id: bsm.InviteId}
						get, err = engine.Get(xiaoErPar)
						if err != nil {
							return nil, err
						}
						if get {
							divs = append(divs, &OrderDivision{
								OrderId:     o.Id,
								OrderCode:   o.Code,
								ProductId:   o.ProductId,
								ProductName: o.ProductName,
								BusinessId:  o.BusinessId,
								DivUserId:   xiaoErPar.Id,
								DivAmount:   division.InviteParentAmount,
								DivLsUser:   xiaoErPar.LsUser,
								DivStatus:   1,
								PayUser:     o.UserName,
								PayUserId:   o.UserId,
							})
							o.CompanyAmount -= division.InviteParentAmount
						}
					} else if division.InviteAmountGive == 2 {
						divs = append(divs, &OrderDivision{
							OrderId:     o.Id,
							OrderCode:   o.Code,
							ProductId:   o.ProductId,
							ProductName: o.ProductName,
							BusinessId:  o.BusinessId,
							DivUserId:   o.UserId,
							DivAmount:   division.InviteParentAmount,
							DivLsUser:   busUser.LsUser,
							DivStatus:   1,
							PayUser:     o.UserName,
							PayUserId:   o.UserId,
						})
						o.CompanyAmount -= division.InviteParentAmount
					}

					// endregion
				} else {
					amount += division.InviteParentAmount
				}
			}
			divs = append(divs, &OrderDivision{
				OrderId:     o.Id,
				OrderCode:   o.Code,
				ProductId:   o.ProductId,
				ProductName: o.ProductName,
				BusinessId:  o.BusinessId,
				DivUserId:   xiaoErUser.Id,
				DivAmount:   amount,
				DivLsUser:   xiaoErUser.LsUser,
				DivStatus:   1,
				PayUser:     o.UserName,
				PayUserId:   o.UserId,
			})
			o.CompanyAmount -= amount
		}

	}

	//endregion

	_, err = engine.ID(o.Id).Update(o)
	if err != nil {
		return nil, err
	}
	_, err = engine.Insert(divs)
	if err != nil {
		return nil, err
	}
	datas := make([]*request_models.DivInfo, 0)
	datas = append(datas, &request_models.DivInfo{
		DivAmt:  int64(o.CompanyAmount * 100),
		TransIn: "3508734202800242622",
	})
	for i, _ := range divs {
		if len(divs[i].DivLsUser) > 0 {
			isNew := true
			for i2, _ := range datas {
				if datas[i2].TransIn == divs[i].DivLsUser {
					datas[i2].DivAmt += int64(divs[i].DivAmount * 100)
					isNew = false
					break
				}
			}
			if isNew {
				datas = append(datas, &request_models.DivInfo{
					DivAmt:  int64(divs[i].DivAmount * 100),
					TransIn: divs[i].DivLsUser,
				})
			}
		}
	}
	return datas, nil
	//orderDivision := &OrderDivision{
	//	Id:                 0,
	//	OrderId:            o.Id,
	//	InviteId:           0,
	//	InviteAmount:       0,
	//	InviteParentId:     0,
	//	InviteParentAmount: 0,
	//	BusinessId:         o.BusinessId,
	//	BusinessAmount:     division.BusinessAmount,
	//	DealerId:           o.DealerId,
	//	DealerAmount:       division.DealerAmount,
	//	Amount:             division.BusinessAmount + division.DealerAmount,
	//}
	//
	//bm := &BusinessMember{MemberId: o.UserId, BusinessId: o.BusinessId}
	//
	//get, err = engine.Get(bm)
	//if err != nil {
	//	return nil, err
	//}
	//if get && bm.InviteId > 0 {
	//	orderDivision.InviteId = bm.InviteId
	//	orderDivision.InviteAmount = division.InviteAmount
	//	orderDivision.Amount += division.InviteAmount
	//}
	//
	//bmp := &BusinessMember{MemberId: bm.InviteId, BusinessId: o.BusinessId}
	//
	//get, err = engine.Get(bm)
	//if err != nil {
	//	return nil, err
	//}
	//if get && bmp.InviteId > 0 {
	//	orderDivision.InviteParentId = bmp.InviteId
	//	orderDivision.InviteParentAmount = division.InviteParentAmount
	//	orderDivision.Amount += division.InviteParentAmount
	//}
	//_, err = engine.Insert(orderDivision)
	//if err != nil {
	//	return nil, err
	//}
	//return orderDivision, nil
}

//func (o *Order) GetDivisionInfo(engine *xorm.Engine) ([]*request_models.DivInfo, error) {
//	infos := make([]*request_models.DivInfo, 0)
//	if o.InviteId > 0 && o.InviteAmount > 0 {
//		invite := &LsUserInfo{UserId: o.InviteId}
//		get, err := engine.Get(invite)
//		if err != nil {
//			return nil, err
//		}
//		if !get {
//			return nil, errors.New("邀请人未完成实名认证")
//		}
//		infos = append(infos, &request_models.DivInfo{
//			DivAmt:      int64(o.InviteAmount * 100),
//			ChannelUser: invite.ChannelUser,
//		})
//	}
//	if o.InviteParentId > 0 && o.InviteParentAmount > 0 {
//		inviteParent := &LsUserInfo{UserId: o.InviteParentId}
//		get, err := engine.Get(inviteParent)
//		if err != nil {
//			return nil, err
//		}
//		if !get {
//			return nil, errors.New("邀请人未完成实名认证")
//		}
//		infos = append(infos, &request_models.DivInfo{
//			DivAmt:      int64(o.InviteParentAmount * 100),
//			ChannelUser: inviteParent.ChannelUser,
//		})
//	}
//	if o.BusinessId > 0 && o.BusinessAmount > 0 {
//		business := &LsUserInfo{UserId: o.BusinessId}
//		get, err := engine.Get(business)
//		if err != nil {
//			return nil, err
//		}
//		if !get {
//			return nil, errors.New("店家未完成实名认证")
//		}
//		infos = append(infos, &request_models.DivInfo{
//			DivAmt:      int64(o.BusinessAmount * 100),
//			ChannelUser: business.ChannelUser,
//		})
//	}
//	if o.DealerId > 0 && o.DealerAmount > 0 {
//		dealer := &LsUserInfo{UserId: o.DealerId}
//		get, err := engine.Get(dealer)
//		if err != nil {
//			return nil, err
//		}
//		if !get {
//			return nil, errors.New("经销商未完成实名认证")
//		}
//		infos = append(infos, &request_models.DivInfo{
//			DivAmt:      int64(o.DealerAmount * 100),
//			ChannelUser: dealer.ChannelUser,
//		})
//	}
//	return infos, nil
//}

type WriteOffRecord struct {
	Id               int64
	OrderId          int64
	UserId           int64
	ProductId        int64
	BusinessId       int64
	ProductName      string
	ProductCover     string
	BusinessName     string
	UserName         string
	WriteOffUserId   int64
	WriteOffUserName string
	WriteOffTime     string
}
